﻿#include "PluginContainerWidget.h"
#include "ui_PluginContainerWidget.h"

#include <QVBoxLayout>
#include <QIcon>

PluginContainerWidget::PluginContainerWidget(IPluginDialog *dlg, QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::PluginContainerWidget)
    , m_curDlg(dlg)
{
    this->setWindowFlags(this->windowFlags() | Qt::WindowMinMaxButtonsHint);
    setAttribute(Qt::WA_DeleteOnClose);

    m_runtimeLabel = new QLabel();
    label = new QLabel(tr("Algorithm run time:"));
    vbLay = new QVBoxLayout(this);
    runtimeLay = new QHBoxLayout(this);
    runtimeLay->addWidget(label);
    runtimeLay->addWidget(m_runtimeLabel);
    runtimeLay->addStretch();
    vbLay->setContentsMargins(10,0,10,2);
    if (m_curDlg)
    {
        setWindowTitle(dlg->getWindowTitle());
        m_curDlg->setVisible(true);
        vbLay->addWidget(m_curDlg, 1);
    }
    vbLay->addLayout(runtimeLay, 0);

    setLayout(vbLay);
    setMinimumSize(1100,630);
    setModal(true);

    reset();
}

PluginContainerWidget::~PluginContainerWidget()
{
    if(nullptr != label)
    {
        delete label;
        label = nullptr;
    }

    if(nullptr != m_runtimeLabel)
    {
        delete m_runtimeLabel;
        m_runtimeLabel = nullptr;
    }
    delete ui;
}

void PluginContainerWidget::setPluginDialog(IPluginDialog *dlg)
{
    m_curDlg = dlg;
    dlg->setVisible(true);
    vbLay->insertWidget(0, dlg, 1);
    setWindowTitle(dlg->getWindowTitle());
    reset();
}

void PluginContainerWidget::closeEvent(QCloseEvent *ev)
{
    if(m_curDlg)
    {
        //m_curDlg->close();
        vbLay->removeWidget(m_curDlg);
        m_curDlg->setParent(nullptr);
        m_curDlg = nullptr;
    }

    QDialog::closeEvent(ev);
}

void PluginContainerWidget::sltUpdateRuntime(float timeMs)
{
    QString strTime = QString::number(timeMs, 'f', 3) + " ms";
    m_runtimeLabel->setText(strTime);
}

void PluginContainerWidget::reset()
{
    m_runtimeLabel->setText("");
}

void PluginContainerWidget::setRuntimeVisible(bool isVisi)
{
    m_runtimeLabel->setVisible(isVisi);
    label->setVisible(isVisi);
}
